<?php

namespace common\entities\common;

use common\entities\ConfigEntity;
use common\services\common\MyscrmContractApplicationService;
use common\support\StringHelper;
use common\repositories\myhtsq\ContractApplicationRepository;
use common\repositories\myhtsq\ContractManageRepository;
use common\entities\myhtsq\ContractPropertyEntity;

/**
 * This is the model class for table "myscrm_organizationtoauthorize".
 *
 * @property string $Id
 * @property string $OrganizationId
 * @property string $ApplicationId
 * @property string $AuthorizeTypeId
 * @property integer $TotalNum
 * @property string $VersionNumber
 * @property string $ContractId
 * @property integer $IsQdAdvanced
 * @property integer $application_info_id
 */
class MyscrmOrganizationToAuthorizeEntity extends ConfigEntity
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'myscrm_organizationtoauthorize';
    }

    public static function globalTableName()
    {
        preg_match("/dbname=([^;]+)/i", self::getDb()->dsn, $matches);
        return $matches[1].'.myscrm_organizationtoauthorize';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [

            [['Id', 'TotalNum', 'VersionNumber'], 'required'],
            [['IsQdAdvanced'], 'integer'],
            [['TotalNum'],'number'],
            [['Id', 'OrganizationId', 'ApplicationId', 'AuthorizeTypeId', 'ContractId', 'application_info_id'], 'string', 'max' => 36],
            [['VersionNumber'], 'string', 'max' => 8],
            [['OrganizationId', 'ApplicationId', 'AuthorizeTypeId', 'ContractId'], 'unique',
                'targetAttribute' => ['OrganizationId', 'ApplicationId', 'AuthorizeTypeId', 'ContractId'],
                'message' => 'The combination of Organization ID, Application ID, Authorize Type ID and Contract ID has already been taken.']

        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'Id' => 'ID',
            'OrganizationId' => 'Organization ID',
            'ApplicationId' => 'Application ID',
            'AuthorizeTypeId' => 'Authorize Type ID',
            'TotalNum' => 'Total Num',
            'VersionNumber' => 'Version Number',
            'ContractId' => 'Contract ID',
            'IsQdAdvanced' => '是否渠道管家旗舰版',
            'application_info_id' => '合同管理的产品id',
        ];
    }
    
    /**
    * 根据租户id,获取租户授权信息列表
    * @param string $organizationId 租户id
    * @param string $contractId 合同id
    * @return array
    */
	public static function getAuthorizeListByOrganizationId($organizationId,$contractId) {
		//sonar 坏味道修复
        return self::find()->where(['ContractId'=>$contractId])->all();
	}

    /**
     * 根据基本信息产品id,获取授权信息中所有的授权数目
     * @param string $organizationId 租户id
     * @param string $ContractApplicationId 合同产品id
     * @return int
     */
    public static function getAuthorizeNumByContractApplicationId($contractapplicationId) {
        return self::find()->where(['ContractApplicationId'=>$contractapplicationId])->asArray()->all();
    }


	/**
     * 根据租户id,新增租户授权
     * @author zhoud01
     * @since 2017-7-23
     * @param array
     * @return boolean
     */
    public static function addAuthorizeByOrganizationId($arr,$fromTenant = false) {

        $status = false;
        $where = [
            'UniqueName' => 'projcount',
            'ApplicationId' => $arr['application_id'],
        ];

        $AuthorizeTypeId = MyscrmAuthorizeTypeEntity::find()->where($where)->asArray()->one();
        $AuthorizeTypeId = $AuthorizeTypeId['AuthorizeTypeId'];

        if(!empty($arr)){
            if($fromTenant){//TODO 来自租户中心
                $addAddAuthor = self::findOne($arr['id']);
                $addAddAuthor->ContractApplicationId = $arr['contract_application_id'];//绑定与基本信息中产品的关系
                $res = $addAddAuthor->save();

                //sonar 坏味道修复
                return $res?$addAddAuthor->attributes['Id']:false;

            }
            $settlement_amount = $arr['settlement_amount'];
            //TODO 计算结算金额
            if($arr['is_joint']){
                $settlement_amount = isset($arr['erp_product_settlement_amount'])?$arr['erp_product_settlement_amount']:$arr['settlement_amount'];
            }
            if(!$settlement_amount){
                $settlement_amount = self::calculationSettlementAmount($arr);
            }

            if($arr['handleType']==='add'){
                $isExistAuthorize = self::findOne($arr['author_id']);
                if(empty($isExistAuthorize)){
                    $addAddAuthor = new MyscrmOrganizationToAuthorizeEntity();
                    $addAddAuthor->Id = $arr['author_id'];
                    $addAddAuthor->OrganizationId = $arr['organization_id'];
                    $addAddAuthor->ApplicationId = $arr['application_id'];
                    $addAddAuthor->application_info_id = $arr['application_id'];
                    $addAddAuthor->AuthorizeTypeId = $AuthorizeTypeId;
                    $addAddAuthor->TotalNum = (int)$arr['total_num'];
                    $addAddAuthor->VersionNumber = date("Ymd",time());
                    $addAddAuthor->ContractId = $arr['contractId'];//考虑保证字段唯一配置库中的哪个

                    $addAddAuthor->SettlementAmount = $settlement_amount;//结算金额 四舍五入后的值
                    $addAddAuthor->SignAmount = isset($arr['sign_amount'])?$arr['sign_amount']:self::calculationSignAmount($arr);//签约金额

                    $addAddAuthor->ProductType = $arr['product_type'];//结算金额
                    $addAddAuthor->ContractApplicationId = $arr['contract_application_id'];//绑定与基本信息中产品的关系
                    $addAddAuthor->IsOpeningPerformance = 2;//标识来源
                    $res = $addAddAuthor->save();

                    $mix['SettlementAmount'] = $addAddAuthor->attributes['SettlementAmount'];
                    $mix['AuthorId'] = $addAddAuthor->attributes['Id'];

                    //sonar 坏味道修复
                    return $res?$mix:false;
                }else{
                    $addAddAuthor = self::findOne($arr['author_id']);
                    if($addAddAuthor == null){
                        return false;
                    }
                    if(!empty($arr['organization_id'])){
                        $addAddAuthor->OrganizationId = $arr['organization_id'];
                    }
                    if(!empty($arr['application_id'])){
                        $addAddAuthor->ApplicationId = $arr['application_id'];
                    }
                    if(isset($arr['total_num']) && (int)$arr['total_num'] >=0){
                        $addAddAuthor->TotalNum = (int)$arr['total_num'];
                    }
                    if(!empty($arr['contract_application_id']) && empty($addAddAuthor->ContractApplicationId)){//会签先出库再有合同的
                        $addAddAuthor->ContractApplicationId = $arr['contract_application_id'];//绑定与基本信息中产品的关系
                    }

                    $addAddAuthor->SettlementAmount = $settlement_amount;//结算金额
                    $addAddAuthor->SignAmount = isset($arr['sign_amount'])?$arr['sign_amount']:self::calculationSignAmount($arr);//签约金额
                    $addAddAuthor->IsModify = 2;//2 记录表示被修改过金额采用

                    if(!empty($arr['product_type'])){
                        $addAddAuthor->ProductType = $arr['product_type'];//1：新增 2：增购 3：续签
                    }

                    $res = $addAddAuthor->save();

                    $mix['SettlementAmount'] = $addAddAuthor->attributes['SettlementAmount'];
                    $mix['AuthorId'] = $addAddAuthor->attributes['Id'];

                    //sonar 坏味道修复
                    return $res?$mix:false;
                }
            }else if($arr['handleType']==='edit'){
                $addAddAuthor = self::findOne($arr['author_id']);
                if($addAddAuthor == null){
                    return false;
                }
                if(!empty($arr['organization_id'])){
                    $addAddAuthor->OrganizationId = $arr['organization_id'];
                }
                if(!empty($arr['application_id'])){
                    $addAddAuthor->ApplicationId = $arr['application_id'];
                }
                if(isset($arr['total_num']) && (int)$arr['total_num'] >=0){
                    $addAddAuthor->TotalNum = (int)$arr['total_num'];
                }
                if(!empty($arr['contract_application_id']) && empty($addAddAuthor->ContractApplicationId)){//会签先出库再有合同的
                    $addAddAuthor->ContractApplicationId = $arr['contract_application_id'];//绑定与基本信息中产品的关系
                }

                $addAddAuthor->SettlementAmount = $settlement_amount;//结算金额
                $addAddAuthor->SignAmount = isset($arr['sign_amount'])?$arr['sign_amount']:self::calculationSignAmount($arr);//签约金额
                $addAddAuthor->IsModify = 2;//2 记录表示被修改过金额采用

                if(!empty($arr['product_type'])){
                    $addAddAuthor->ProductType = $arr['product_type'];//1：新增 2：增购 3：续签
                }
                
                $res = $addAddAuthor->save();

                $mix['SettlementAmount'] = $addAddAuthor->attributes['SettlementAmount'];
                $mix['AuthorId'] = $addAddAuthor->attributes['Id'];

                //sonar 坏味道修复
                return $res?$mix:false;
            } else {
                if(!empty($arr['id'])){// 如果有id表示为修改

                    $addAddAuthor = self::findOne($arr['id']);
                    if($addAddAuthor == null){
                        return false;
                    }
                    if(!empty($arr['organization_id'])){
                        $addAddAuthor->OrganizationId = $arr['organization_id'];
                    }
                    if(!empty($arr['application_id'])){
                        $addAddAuthor->ApplicationId = $arr['application_id'];
                    }
                    if(!empty($arr['total_num'])){
                        $addAddAuthor->TotalNum = (int)$arr['total_num'];
                    }
                    $addAddAuthor->SettlementAmount = $arr['settlement_amount'];//结算金额
                    $addAddAuthor->SignAmount = isset($arr['sign_amount'])?$arr['sign_amount']:self::calculationSignAmount($arr);//签约金额
                    $addAddAuthor->IsModify = 2;//2 记录表示被修改过金额采用

                    if(!empty($arr['product_type'])){
                        $addAddAuthor->ProductType = $arr['product_type'];//1：新增 2：增购 3：续签
                    }
                    $res = $addAddAuthor->save();
                    //sonar 坏味道修复
                    return $res?$addAddAuthor->attributes['Id']:false;
                }else{
                    $addAddAuthor = new MyscrmOrganizationToAuthorizeEntity();
                    $addAddAuthor->Id = StringHelper::uuid();
                    $addAddAuthor->OrganizationId = $arr['organization_id'];
                    $addAddAuthor->ApplicationId = $arr['application_id'];
                    $addAddAuthor->application_info_id = $arr['application_id'];
                    $addAddAuthor->AuthorizeTypeId = $AuthorizeTypeId;
                    $addAddAuthor->TotalNum = (int)$arr['total_num'];
                    $addAddAuthor->VersionNumber = date("Ymd",time());
                    $addAddAuthor->ContractId = $arr['contractId'];//考虑保证字段唯一配置库中的哪个

                    $addAddAuthor->SettlementAmount = $settlement_amount;//结算金额 四舍五入后的值
                    $addAddAuthor->SignAmount = isset($arr['sign_amount'])?$arr['sign_amount']:self::calculationSignAmount($arr);//签约金额

                    $addAddAuthor->ProductType = $arr['product_type'];//结算金额
                    $addAddAuthor->ContractApplicationId = $arr['contract_application_id'];//绑定与基本信息中产品的关系
                    $addAddAuthor->IsOpeningPerformance = 2;//标识来源
                    $res = $addAddAuthor->save();

                    $mix['SettlementAmount'] = $addAddAuthor->attributes['SettlementAmount'];
                    $mix['AuthorId'] = $addAddAuthor->attributes['Id'];

                    //sonar 坏味道修复
                    return $res?$mix:false;
                }
            }
        }

        return $status;
    }

    /**
     * 结算金额计算
     * @author zhoud01
     * @since 2017-9-06
     * @param array
     * @return string
     */
    public static function calculationSettlementAmount($arr) {

        $contractModel = ContractManageRepository::getContractManageModelByContractId($arr['contract_id']); // 获取model
        $contractAndApp = ContractApplicationRepository::getContractApplicationAppId($arr['contract_application_id']);
        $contractAndAppAll = ContractApplicationRepository::getContractApplicationByContractId($arr['contract_id']);

        $settlement_amount = $arr['settlement_amount'];
        $authorization_numeric = $contractAndApp->authorization_numeric;

        $allAmount = 0;
        foreach ($contractAndAppAll as $item){
            $allAmount += $item['amount'];
        }

        //解决除数为0情况
        $allAmount = empty($allAmount)?1:$allAmount;
        $authorization_numeric = empty($authorization_numeric)?1:$authorization_numeric;

        $scale = (int)$arr['total_num'] / $authorization_numeric;

        if($arr['matching_rule'] ==2 && $arr['delivery_rules'] ==1){
            $scale = 1;
        }

        if($contractAndApp->settlement_type == 1) {//1.标准结算  当次已出数目/产品数*标准总额*结算比例
            $settlement_amount = $scale * $contractAndApp->amount * $contractAndApp->settlement_scale / 100;
        }

        if($contractAndApp->settlement_type == 2) {//2.折上折结算 当次已出数目/产品数*标准总额*结算比例*折扣
            $settlement_amount = $scale * $contractAndApp->amount * $contractAndApp->settlement_scale / 100 * $contractAndApp->discount / 100;
        }

        if($contractAndApp->settlement_type == 3) {//3.特价结算 当次已出数目/产品数*签约总额*结算比例
            $settlement_amount = ($scale * $contractAndApp->amount) / $allAmount * $contractModel->sign_amount * $contractAndApp->settlement_scale / 100;
        }

        return $settlement_amount;
    }

    /**
     * 签约金额计算
     * @author zhoud01
     * @since 2018-02-01
     * @param array
     * @return string
     */
    public static function calculationSignAmount($arr)
    {
        $contractModel = ContractManageRepository::getContractManageModelByContractId($arr['contract_id']); // 获取model
        $contractAndApp = ContractApplicationRepository::getContractApplicationAppId($arr['contract_application_id']);
        $sign_amount = $arr['settlement_amount'];
        $authorization_numeric = empty($authorization_numeric)?1:$authorization_numeric;
        $scale = (int)$arr['total_num'] / $authorization_numeric;

        if($arr['matching_rule'] ==2 && $arr['delivery_rules'] ==1){
            $scale = 1;
        }

        $checkArr = [
            ContractPropertyEntity::MYYK_PROPERTY_DIRECTLY_UNDER_ID,//云客签约-直属
            ContractPropertyEntity::MYYK_PROPERTY_JOINT_OPERATION_ID,//云客签约-直属区域
            ContractPropertyEntity::MYYK_PROPERTY_DIRECT_SALES_ID,//云客直销
        ];

        //云客类合同采取标结100%结算
        if(in_array($contractModel->contract_property_id,$checkArr)){
            $appRes = MyscrmContractApplicationService::getApplicationInfoByApplicationId($arr['application_id']);//产品基本信息
            $getContractApplication = ContractApplicationRepository::getContractApplicationByContractId($arr['contract_id']);//合同下基本信息产品
            $sign_amount = $contractModel->sign_amount;//签约金
            $authorization_numeric = $contractAndApp->authorization_numeric;//产品基本信息授权数
            $matchingRule = $appRes['matching_rule'];//产品匹配规则
            $delivery_rules = $appRes['delivery_rules'];//业绩完成规则
            //TODO 需要该条的标准总额
            $StandardAmount = $contractAndApp->amount;

            //TODO 需要标准总额合计
            $StandardAmountAll = 0;
            foreach ($getContractApplication as $app){
                $StandardAmountAll += $app['amount'];//标准总额合计
            }

            $authorization_numeric = empty($authorization_numeric)?1:$authorization_numeric;

            //Division by zero
            if($StandardAmountAll == 0){
                $StandardAmountAll = 1;
            }

            $formula = (int)$arr['total_num']/(int)$authorization_numeric*(int)$StandardAmount/(int)$StandardAmountAll;

            if($delivery_rules == 1 && $matchingRule ==2&&(int)$StandardAmountAll!=0){//TODO $formula2A 按产品名称
                $formula = (int)$StandardAmount/(int)$StandardAmountAll;//该产品的标准总额 / 总标准总额 * 基本信息的产品租金金额
            }
            return round(floatval($formula*$sign_amount),2);//签约分摊金

//            $contractAndApp->settlement_type = 1;
//            $contractAndApp->settlement_scale = 100;
        }else{
            $contractAndApp->settlement_type = 1;
            $contractAndApp->settlement_scale = 0;
        }

        if($contractAndApp->settlement_type == 1) {//1.标准结算  当次已出数目/产品数*标准总额*结算比例
            $sign_amount = $scale * $contractAndApp->amount * $contractAndApp->settlement_scale / 100;
        }

        return $sign_amount;
    }

    public static function calculationSignAmountForYk($arr){
        $contractModel = ContractManageRepository::getContractManageModelByContractId($arr['contract_id']); // 获取model
        $contractAndApp = ContractApplicationRepository::getContractApplicationAppId($arr['contract_application_id']);
        $appRes = MyscrmContractApplicationService::getApplicationInfoByApplicationId($arr['application_id']);//产品基本信息
        $getContractApplication = ContractApplicationRepository::getContractApplicationByContractId($arr['contract_id']);//合同下基本信息产品
        $sign_amount = $contractModel->sign_amount;//签约金

        $authorization_numeric = $contractAndApp->authorization_numeric;//产品基本信息授权数
        $matchingRule = $appRes['matching_rule'];//产品匹配规则
        $delivery_rules = $appRes['delivery_rules'];//业绩完成规则
        //TODO 需要该条的标准总额
        $StandardAmount = $contractAndApp->amount;

        //TODO 需要标准总额合计
        $StandardAmountAll = 0;
        foreach ($getContractApplication as $app){
            $StandardAmountAll += $app['amount'];//标准总额合计
        }

        $authorization_numeric = empty($authorization_numeric)?1:$authorization_numeric;

        //Division by zero
        if($StandardAmountAll == 0){
            $StandardAmountAll = 1;
        }

        $formula = (int)$arr['total_num']/(int)$authorization_numeric*(int)$StandardAmount/(int)$StandardAmountAll;

        if($delivery_rules == 1 && $matchingRule ==2&&(int)$StandardAmountAll!=0){//TODO $formula2A 按产品名称
            $formula = (int)$StandardAmount/(int)$StandardAmountAll;//该产品的标准总额 / 总标准总额 * 基本信息的产品租金金额
        }
        return round($formula*$sign_amount);//签约分摊金
    }


    public static function getContractOrderSummary($contractNum) {

        return self::find()->select("myscrm_contract.EstablishTime,
                            myscrm_contract.PerformanceAccountingTime,
                            myscrm_contract.BeginOn,myscrm_contract.EndOn,
                            myscrm_organizationtoauthorize.SettlementAmount,
                            myscrm_organizationtoauthorize.SignAmount,
                            myscrm_organizationtoauthorize.ApplicationId,
                            myscrm_organizationtoauthorize.Id,myscrm_organizationtoauthorize.ProductType,
                            myscrm_organizationtoauthorize.IsQdAdvanced,
                            myscrm_organizationtoauthorize.ContractApplicationId,
                            myscrm_organizationtoauthorize.application_info_id
                            ")
                            ->innerJoin("myscrm_contract", "myscrm_organizationtoauthorize.ContractId = myscrm_contract.ContractId")
                            ->where(['ContractNum'=>$contractNum])
                            ->andWhere(['>','TotalNum',0])//取开通数目大于0的
                            ->asArray()
                            ->all();

    }

    /**
     * 得到授权数
     * @param $organizationId
     * @param $contractId
     * @param $applicationId
     * @return null|static
     */
    public static function getAuthorize($organizationId, $contractId, $applicationId){
        return self::findOne([
            'OrganizationId'=>$organizationId,'ContractId'=>$contractId, 'ApplicationId' => $applicationId
        ]);
    }
}
